package com.education.wisdom.controller;


import com.education.common.pojo.ResourceVO;
import com.education.common.utils.ApiReturnObject;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.feign.WelcoFeign;
import com.education.wisdom.pojo.Resources;
import com.education.wisdom.service.ICatalogService;
import com.education.wisdom.service.IResourcesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/web/resources")
public class FullResourcesController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private WelcoFeign welcoFeign;

    @Autowired
    private ICatalogService catalogService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 同步虚拟教学
     *
     * @return
     * @catalogId : 三级目录id 查询虚拟教学
     * @parentId : 同步到的课程的parnetId
     */
    @GetMapping("/synchronousVirtual")
    public ApiReturnObject synchronousVirtual(String[] catalogId, Integer parentId, Integer userId) {
        Object count = redisTemplate.opsForValue().get("count" + userId);
        int i = 0;
        if (count == null) {
            count = 1;
        }
        i = Integer.parseInt(count.toString());
        if (i <= 5) {
            //查询用户达人币
            Map<String, Object> use = userFeign.selectByUserId(userId);
            BigDecimal price = new BigDecimal(use.get("price").toString());
            //修改用户达人币
            Map<String, Object> map = new HashMap<>();
            map.put("id", userId);
            Random random = new Random();
            int j = random.nextInt(5) + 1;
            //map.put("price", price + j);
            map.put("price", price.add(new BigDecimal(j)));
            userFeign.updatePriceByUserId(userId, price.add(new BigDecimal(j)));
        }
        redisTemplate.opsForValue().set("count" + userId, i + 1);
        String flash = null;
        String threeD = null;
        String name = null;
        //查询课程是否有4级目录
        //查询课程下的 3D flash视频
        for (String ca : catalogId) {
            Map<String, Object> map = new HashMap<>();
            map.put("rCatalogid", ca);
            List<Resources> resources = resourcesService.selectVideoById(map);
            for (Resources resource : resources) {
                name = resource.getrName();
                if (resource.getType().equals("9")) {
                    flash = resource.getrUrl();
                }
                if (resource.getType().equals("8")) {
                    threeD = resource.getrUrl();
                }
            }
            if (resources.size() == 1) {
                for (Resources resource : resources) {
                    if (resource.getType().equals("8")) {
                        threeD = resource.getrUrl();
                    } else {
                        threeD = "0";
                    }
                    if (resource.getType().equals("9")) {
                        flash = resource.getrUrl();
                    } else {
                        flash = "0";
                    }
                }
            }
            //同步资源
            StringBuilder builder = new StringBuilder();
            StringBuilder append = builder.append(threeD).append(",").append(flash);
            ResourceVO vo = new ResourceVO();
            vo.setRUrl(append.toString());
            vo.setRName(name);
            vo.setCatalogId(parentId);
            welcoFeign.insertResourcesVirtual(vo);
        }
        return new ApiReturnObject("200", "success", "");
    }

    /**
     * 同步资源
     *
     * @return
     * @parentId : 要同步到的课程id
     */
    @GetMapping("/synchronous")
    public ApiReturnObject synchronous(String[] ids, Integer parentId, Integer userId) {
        Object count = redisTemplate.opsForValue().get("count" + userId);
        int i = 0;
        if (count == null) {
            count = 1;
        }
        i = Integer.parseInt(count.toString());
        if (i <= 5) {
            //查询用户达人币
            Map<String, Object> use = userFeign.selectByUserId(userId);
            BigDecimal price = new BigDecimal(use.get("price").toString());
            //修改用户达人币
            Map<String, Object> map = new HashMap<>();
            map.put("id", userId);
            Random random = new Random();
            int j = random.nextInt(5) + 1;
            //map.put("price", price + j);
            map.put("price", price.add(new BigDecimal(j)));
            //userFeign.updataByUserId(map);
            userFeign.updatePriceByUserId(userId, price.add(new BigDecimal(j)));
        }
        redisTemplate.opsForValue().set("count" + userId, i + 1);
        List<Resources> resources = resourcesService.selectByIds(ids);
        List<ResourceVO> list = new ArrayList<>();
        if (resources.size() > 0) {
            for (Resources resource : resources) {
                ResourceVO vo = new ResourceVO();
                //同步到的课程id
                vo.setCatalogId(parentId);
                BeanUtils.copyProperties(resource, vo);
                list.add(vo);
            }
        }

        for (ResourceVO resourceVO : list) {
            String s = welcoFeign.insertResources(resourceVO);
            if ("1".equals(s)) {
                logger.info("同步 : {} 成功", resourceVO.getRName());
                //return new ApiReturnObject("200", "success", "");
            }
        }
        return new ApiReturnObject("200", "success", "");
    }


    /**
     * 将智慧云资源同步到新今软平台
     */
    @GetMapping("/tongBuRes")
    public String tongBuRes(Integer catalogId) {
        List<ResourceVO> resourceVo = welcoFeign.resourceVOList(catalogId);
        Resources resources = new Resources();
//        Catalog catalog = new Catalog();
//        catalog.setParentId(2681);
//        catalog.setCreateTime(new Date());
        for (ResourceVO resourceVO : resourceVo) {
            //新建catalog目录
//            catalog.setCatalogId(null);
//            catalogService.insertCatalog(catalog);
            BeanUtils.copyProperties(resourceVO, resources);
            resources.setrCatalogid(2682);
            resources.setType("1");
            resourcesService.insertResources(resources);
        }
        return resourceVo.size() + "";
    }


    @GetMapping("/addRes")
    public String addRes(Integer catalogId, String type, String suffix) {
        Resources resources = new Resources();

        //遍历文件夹下所有单个文件尽心操作转移s
        File file = new File("H:\\智慧云11.05新版资源\\3.7.动力电池和管理系统虚拟软件\\1.教学课件\\");
        //获取文件夹下所有文件
        File[] files = file.listFiles();
        if (files == null) {
            System.out.println("failed");
            return "失败";
        }
        //遍历 匹配
        for (File file1 : files) {
            if (file1.isDirectory()) {
                continue;
            }
            resources.setrCatalogid(catalogId);
            resources.setRemark("");
            resources.setType(type);
            resources.setrState("0");
            resources.setCreateTime(new Date());
            resources.setrName(file1.getName());
            resources.setFreeFlag("1");
            resources.setDelFlag("0");
            resources.setrProfessionid("2987");
            resources.setrProfessionname("焊接技术类");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long l = System.currentTimeMillis();
            resources.setrUrl(l + suffix);
            //重命名 移至另一个文件夹内
            boolean b = file1.renameTo(new File("H:\\智慧云11.05新版资源\\3.7.动力电池和管理系统虚拟软件\\1.教学课件\\new\\" + l + suffix));
            if (b) {
                resourcesService.insertResources(resources);
            }
        }
        return "完成";
    }


}
